package net.qunzhi.modules.cms.websocket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * websocket服务
 * Created by lsd
 * 2019-08-26 10:35
 */
@Component
@ServerEndpoint("/websocket/{username}")
public class WebSocketServer {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * 在线人数
     */
    public static int onlineNumber = 0;
    /**
     * 以用户的姓名为key，WebSocketServer对象本身保存起来
     */
    private static Map<String, WebSocketServer> clients = new ConcurrentHashMap();
    /**
     * 会话
     */
    private Session session;
    /**
     * 用户名称
     */
    private String username;

    /**
     * 建立连接
     */
    @OnOpen
    public void onOpen(@PathParam("username") String username, Session session) {
        onlineNumber++;
        logger.info("现在来连接的客户id：" + session.getId() + "用户名：" + username);
        this.username = username;
        this.session = session;
        logger.info("有新连接加入！ 当前在线人数" + onlineNumber);
        //把自己的信息加入到map当中去
        clients.put(username, this);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        logger.info("服务端发生了错误" + error.getMessage());
        //error.printStackTrace();
    }

    /**
     * 连接关闭
     */
    @OnClose
    public void onClose() {
        onlineNumber--;
        clients.remove(username);
        logger.info("有连接关闭！ 当前在线人数" + onlineNumber);
    }

    /**
     * 收到客户端的消息
     *
     * @param message 消息
     * @param session 会话
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        logger.info("来自客户端消息：" + message + "客户端的id是：" + session.getId());
        // 心跳消息
        if(message.equals("ping")){
            session.getAsyncRemote().sendText("pong");
        }
    }


    //遍历所有在线用户，发送消息到toUserName的用户
    public void sendMessageTo(String message, String toUserName) throws IOException {
        for (WebSocketServer item : clients.values()) {
            if (item.username.equals(toUserName)) {
                logger.info("推送消息给超级管理员：" + toUserName + " msg=" + message);
                item.session.getAsyncRemote().sendText(message);
                break;
            }
        }
    }

    public void sendMessageAll(String message) throws IOException {
        for (WebSocketServer item : clients.values()) {
            logger.info("推送消息给所有client, msg=" + message);
            item.session.getAsyncRemote().sendText(message);
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineNumber;
    }

}
